import React, { ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
import { LeftOutline, SearchOutline, UserOutline } from 'antd-mobile-icons';
import classNames from 'classnames';
import bem from '@/utils/bem';
import './navbar.scss';

export interface NavBarProps {
    backIcon?: ReactNode | boolean;
    /**
     * 是否固定
     */
    fixed?: boolean;
    /**
     * 左侧内容
     */
    left?: ReactNode | string;
    /**
    * 左侧内容回调函数
    */
    leftOnClick?: () => void | null;

    rightOnClick?: () => void | null;
    /**
     * 是否显示搜索框
     */
    search?: boolean;
    /**
     * 内容区域内容
     */
    content?: ReactNode | string;
    /**
     * 内容区域点击事件处理函数
     */
    contentOnClick?: () => void;
    /**
     * 右侧内容
     */
    right?: ReactNode;
    style?: React.CSSProperties;
}

const b = bem('navbar');

const defaultProps: NavBarProps = {
    backIcon: false,
    fixed: false,
    leftOnClick: undefined,
    left: null,

    search: true,
    content: null,
    contentOnClick: () => {},
    rightOnClick: () => {},
    right: null,
    style: {},
};

const NavBar: React.FC<NavBarProps> = (props) => {
    const {
        backIcon,
        fixed,
        leftOnClick,
        left,
        search,
        content,
        right,
        contentOnClick,
        rightOnClick,
        style,
        ...rest
    } = {
        ...defaultProps,
        ...props
    };

    const navigate = useNavigate();
    // 点击返回事件
    const leftOnClickHandler = () => {
        if (leftOnClick) {
            leftOnClick();
        } else {
            navigate(-1);
        }
    };

    const renderLeftContent = () => {
        if (typeof backIcon === 'boolean' && backIcon) {
            return <LeftOutline />;
        }
        return left;
    };

    // 判断点击事件是否存在
    const contentClickHandler = () => {
        return contentOnClick ? contentOnClick() : undefined;
    }
    const renderContent = () => {
        if (search && !content) {
            return (
                <>
                    <div className={b('search')}>
                        <div className={b('search__icon')}>
                            <SearchOutline />
                        </div>
                        <input type="text" className={b('search__input')} placeholder="搜索" />
                    </div>
                </>
            );
        }
        return content;
    };


    return (
        <div className={classNames(b(), fixed && b('fixed'))} style={style}>
            <div className={b('left')} onClick={leftOnClickHandler} >{renderLeftContent()}</div>
            <div className={b('content')} onClick={contentClickHandler}>
                {renderContent()}
            </div>
            <div className={b('right')} onClick={rightOnClick}>{right}</div>
        </div>
    );
};

export default NavBar;